package org.example.spring.self.demo;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

/**
 * 文件描述
 *
 * @author yezhou41127
 * @date: 2022年08月01日
 */
public class TestApplicationContext {

	public static void main(String[] args) {
//		testClassPathXmlApplicationContext();
//		testFileSystemXmlApplicationContext();
		testAnnotationConfigApplicationContext();

/*		DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
		for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) {
			System.out.println(beanDefinitionName);
		}

		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
		reader.loadBeanDefinitions(new ClassPathResource("b01.xml"));
		for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) {
			System.out.println(beanDefinitionName);
		}*/
	}

	/**
	 * 基于 classpath 下 xml 格式配置文件
	 */
	private static void testClassPathXmlApplicationContext() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("b01.xml");

		for (String beanDefinitionName : context.getBeanDefinitionNames()) {
			System.out.println(beanDefinitionName);
		}

		System.out.println(context.getBean(Bean2.class).getBean1());
	}

	/**
	 * 基于磁盘路径
	 */
	private static void testFileSystemXmlApplicationContext() {
		FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(
				// 绝对路径
				"D:\\code\\java\\myself\\spring-framework-5.3.17\\spring-self\\src\\main\\resources\\b01.xml");
		// 相对路径

		for (String beanDefinitionName : context.getBeanDefinitionNames()) {
			System.out.println(beanDefinitionName);
		}

		System.out.println(context.getBean(Bean2.class).getBean1());
	}

	private static void testAnnotationConfigApplicationContext() {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
		for (String beanDefinitionName : context.getBeanDefinitionNames()) {
			System.out.println(beanDefinitionName);
		}

		System.out.println(context.getBean(Bean2.class).getBean1());
	}

	@Configuration
	static class Config {

		@Bean
		public Bean1 bean1() {
			return new Bean1();
		}

		@Bean
		public Bean2 bean2(Bean1 bean1) {
			Bean2 bean2 = new Bean2();
			bean2.setBean1(bean1);
			return bean2;
		}
	}

	static class Bean1 {
	}

	static class Bean2 {
		private Bean1 bean1;

		public Bean1 getBean1() {
			return bean1;
		}

		public void setBean1(Bean1 bean1) {
			this.bean1 = bean1;
		}
	}
}
